package com.example.androidlearning2200.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.androidlearning2200.R;
import com.example.androidlearning2200.bean.MsgBean;

import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.RVHolder> {

    private static final int TYPE_LAYOUT_1 = 1;
    private static final int TYPE_LAYOUT_2 = 2;

    private List<MsgBean> datas;

    public ChatAdapter(List<MsgBean> msgBeans) {
        this.datas = msgBeans;
    }

    @NonNull
    @Override
    public RVHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_LAYOUT_1:
                return new RVHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_receive, parent, false));
            case TYPE_LAYOUT_2:
                return new RVHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_send, parent, false));
            default:
                throw new IllegalArgumentException("Invalid view type");
        }

    }

    /**
     * 给每一个列表项填充内容
     *
     * @param holder   The ViewHolder which should be updated to represent the contents of the
     *                 item at the given position in the data set.
     * @param position The position of the item within the adapter's data set.
     */
    @Override
    public void onBindViewHolder(@NonNull RVHolder holder, int position) {
        MsgBean msgBean = datas.get(position);
        holder.tvName.setText(msgBean.getName());
        holder.tvMsg.setText(msgBean.getMsg());
    }

    @Override
    public int getItemViewType(int position) {
        return datas.get(position).getName().equals("我") ? TYPE_LAYOUT_2 : TYPE_LAYOUT_1;
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    /**
     * 列表项包装器
     */
    public class RVHolder extends RecyclerView.ViewHolder {

        private TextView tvName;
        private TextView tvMsg;

        public RVHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
            tvMsg = itemView.findViewById(R.id.tvMsg);
        }

    }

}
